package org.jcat.toolkit.activemq;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import javax.jms.*;
import java.io.Serializable;

/**
 * Created by hejinxu on 2017/3/24.
 */
public class Sender1 {


    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionfactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
        //创建与JMS服务的连接:ConnectionFactory被管理的对象，由客户端创建，用来创建一个连接对象
        Connection connection = connectionfactory.createConnection();//获取连接，connection一个到JMS系统提供者的活动连接
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//打开会话，一个单独的发送和接受消息的线程上下文
        Sender1 sender1 = new Sender1();

        sender1.sendTextMsg(session, "使用jms发送文本消息", "queue.msgText");//发送文本类型的消息

        MapMessage mapMsg = session.createMapMessage();
        mapMsg.setString("name", "李寻欢1");
        mapMsg.setBoolean("IsHero", true);
        mapMsg.setInt("age", 35);
        sender1.sendMap(session, mapMsg, "queue.msgMap");//发送map类型的消息

        Person person = new Person("阿飞", 23, "北京.大兴");//发送Object类型消息
        sender1.sendObj(session, person, "queue.msgObj");

        session.close();
        connection.close();
    }

    /*
     * 发送文本消息
     */
    public void sendTextMsg(Session session, String MsgContent, String name) throws JMSException {
        Queue queue = new ActiveMQQueue(name);
        MessageProducer msgProducer = session.createProducer(queue);
        Message msg = session.createTextMessage(MsgContent);
        msgProducer.send(msg);
        System.out.println("文本消息已发送");
    }

    /*
     * 发送MAP类型消息
     */
    public void sendMap(Session session, MapMessage map, String name) throws JMSException {
        Queue queue = new ActiveMQQueue(name);
        MessageProducer msgProducer = session.createProducer(queue);
        msgProducer.send(map);
        System.out.println("Map格式的消息已发送");
    }

    /*
     * 发送Object类型消息
     */
    public void sendObj(Session session, Object obj, String name) throws JMSException {
        Destination queue = new ActiveMQQueue(name);//分装消息的目的标示
        //MessageProducer msgProducer = session.createProducer(queue);
        ObjectMessage objMsg = session.createObjectMessage((Serializable) obj);//发送对象时必须让该对象实现serializable接口
        MessageProducer msgPorducer = session.createProducer(queue);
        msgPorducer.send(objMsg);
        System.out.println("Object类型的消息已发送");

    }


}
